 const express=require('express');
 const router= express.Router();

 const bcrypt =require('bcryptjs')
 const  fs =require('fs')
 var userscollection = fs.readFileSync('usercollection.json')
 var users = JSON.parse (userscollection)
 
 const User =require('../models/users');

//  router.use(function(req, res, next) {
//   res.header("Access-Control-Allow-Origin", "*"); 
//   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
//   next();
// });
 router.get(`/users`,(req, res) => {

  
   var allusers =[]
   var allusersinfo= Object.values(users)
   console.log(allusersinfo)
  //  var allusersinfoparsed =JSON.parse(allusersinfo)
     allusersinfo.forEach(people => allusers.push(people.name))
  //  for (var user in users){
  //    console.log(JSON.stringify(user["name"]))
  //    console.log(`${JSON.parse(JSON.stringify(user))}`)
  //   //  var parsUser = json.JSON.parse(user)
  //   //  allusers.push(user["name"])
  //  }
  // console.log(allusersinfoparsed)

  //  res.json(users[`user05 18:34`].name)
  //  res.json(JSON.stringify(allusersname))
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
  res.json(allusers)
 })
 
 router.post(`/users`, async (req, res) => {
   
   if(users[req.body.name]){ alert('用户已存在')}
   else{
   try {
     const hashedPassword = await bcrypt.hash(req.body.password, 10)
     const user = { name: req.body.name, password: hashedPassword }
     console.log(JSON.stringify(user))
    //  users["user"+Date.now.toString]=user
    let date_ob = new Date();

    let date = ("0" + date_ob.getDate()).slice(-2);

    let hours = date_ob.getHours();

    let minutes = date_ob.getMinutes();

    var timeob =(date + " " + hours + ":" + minutes  );

    var time =timeob.toString()
    // users[("user"+time).name] =req.body.name 
    users["user"+time]= {"name" :req.body.name ,"password" : hashedPassword}


     fs.writeFile('usercollection.json', `${JSON.stringify(users,null,4)}`,(err) => {
      if (err) throw err;
      console.log('The file has been saved!');
    });
     res.status(201).send('注册成功') 
   } catch (error){
     
     res.send(error)
     console.log(error)
    //  res.status(500).send('无法接收')
    //  res.status(400).send('无法处理')
   }
 }
 }
 )

 
 router.post(`/users/login`, async (req, res) => {
  var usersKEY =[]

  var allusersinfo= Object.values(users)
  // console.log(allusersinfo)
    allusersinfo.forEach(people => usersKEY[people.name]=people.password)
    
    console.log(usersKEY)
   const usercheck =allusersinfo.find(oneuserinfo => oneuserinfo.name === req.body.name )
   if (usercheck == null) {
     return res.status(400).send('Cannot find user')
   }
   try {
     if(await bcrypt.compare(req.body.password, usersKEY[req.body.name])) {
      console.log(req.body)
      var loginuser=new User(req.body)
      
      loginuser.save()
       res.send('已登陆，可进行问答')
     } else {
       res.send('密码错误')
     }
   } catch {
     res.status(500).send('服务器无法处理')
   }
 })
  
   
 






 module.exports= router